# 通用工具
import os
import shutil
import re

UTF_8 = 'utf-8'
NEW_LINE_LF = '\n'
NEW_LINE_CR_LF = '\r\n'
REG_FILE = re.compile('.+\\..+')
_version = "'2305.2'"


def open_file_as_utf8(file):
    return open(file, 'r', encoding=UTF_8)


def create_utf8_file(file, new_line=NEW_LINE_LF):
    return open(file, 'w', encoding=UTF_8, newline=new_line)


def open_file_as_utf8_for_append(file, new_line=NEW_LINE_LF):
    return open(file, 'a', encoding=UTF_8, newline=new_line)


def write_dict_head(out, name='keypad', version=None, import_tables=None, comment=None):
    out.write('''# Rime dictionary
# Generate by imeasy: https://gitee.com/zelde/imeasy
# encoding: utf-8
''')
    if comment is not None:
        out.write('# {}\n'.format(comment))
    out.write('---\n')
    out.write('name: {}\n'.format(name))
    out.write('version: {}\n'.format(version or _version))
    out.write('''sort: by_weight
use_preset_vocabulary: false     # 不使用已有词组
''')
    if import_tables and len(import_tables) > 0:
        out.write('import_tables:\n')
        for i in import_tables:
            out.write('  - {}\n'.format(i))
    out.write('''columns:
  - text
  - code
  - weight
''')


def is_file_exists(f):
    return os.path.isfile(f)


def empty_dir(target_dir):
    shutil.rmtree(target_dir, ignore_errors=True)
    os.mkdir(target_dir)


def copy_files(from_dir, to_dir, includes=None):
    pattern = re.compile(includes) if includes is not None else REG_FILE
    for file in os.listdir(from_dir):
        if pattern.match(file):
            shutil.copy('{}/{}'.format(from_dir, file), '{}/{}'.format(to_dir, file))


def copy_dir(src_dir, to_dir):
    shutil.copytree(src_dir, to_dir)


def move_files(from_dir, to_dir, includes=None):
    pattern = re.compile(includes) if includes is not None else REG_FILE
    for file in os.listdir(from_dir):
        if pattern.match(file):
            shutil.move('{}/{}'.format(from_dir, file), '{}/{}'.format(to_dir, file))


def bundle(root_dir, to_file):
    shutil.make_archive(to_file, 'zip', root_dir)
